package com.example.shuma_product.filter;

import com.alibaba.fastjson2.JSONObject;
import com.example.shuma_product.errorcode.BaseErrorCode;
import com.example.shuma_product.exception.ClientException;
import com.example.shuma_product.result.Result;
import com.example.shuma_product.result.Results;
import com.example.shuma_product.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.example.shuma_product.errorcode.BaseErrorCode.USER_NOT_LOGIN;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求的url
        String url = req.getRequestURL().toString();

        //2.判断url中是否包含login
        if(url.contains("login")){
            log.info("登录操作放行");
            chain.doFilter(request,response);
            return;
        }

        //3.获取请求头中的令牌
        String jwt = req.getHeader("token");

        //4.判断令牌是否为空
        if(!StringUtils.hasLength(jwt)){
            /*
            Result<Void> failure = Results.failure(USER_NOT_LOGIN);
            String s = JSONObject.toJSONString(failure);
            resp.getWriter().write(s);
             */
            throw new ClientException("用户未登录");
        }

        //5.令牌不为空，校验令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClientException("用户未登录");
        }

        //6.令牌正确，放行
        chain.doFilter(request,response);
    }
}
